//
//  Status.swift
//  HMWeibo08
//
//  Created by 唐万超 on 15/8/2.
//  Copyright © 2015年 唐万超. All rights reserved.
//

import UIKit
import SDWebImage

/// 微博模型
class Status: NSObject {
    
    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id: Int = 0
    /// 微博信息内容
    var text: String?
    /// 微博来源
    var source: String?
    /// 配图数组
    var pic_urls: [[String: AnyObject]]? {
        didSet{
            
            if storedPictureURLs?.count == 0 {
                return
            }
            // 实例化数组
            storedPictureURLs = [NSURL]()
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"] as? String {
                    storedPictureURLs?.append(NSURL(string: urlString)!)
                }
            }
        }
    }
    
    
    /// 配图图片的URL(计算型属性)
    var picURLs: [NSURL]? {
    
        return retweeted_status == nil ? storedPictureURLs : retweeted_status!.storedPictureURLs
    }
    
    /// 保存配图的URL数组  (私有存储性私有属性)
    private var storedPictureURLs: [NSURL]?
    
    /// 微博所需要的行高
    var rowHeight: CGFloat?
    
    /// 用户信息
    var user: User?
    
    /// 转发微博的属性
    var retweeted_status: Status?
    
    // MARK: - 加载模型数据（类方法加载）
    class func loadStatus(since_id: Int, max_id: Int, finished: (dataList:[Status]?, error:NSError?) -> () ) {
        
        NetworkTools.sharedNetworkTools.loadStatus(since_id, max_id: max_id) { (result, error) -> () in
            
            // print(result["statuses"])
            // 判断错误并上传
            if error != nil {
                // 上传错误
                finished(dataList: nil, error: error)
                return
            }
            // 获取返回的微博数组
            if let array = result?["statuses"] as? [[String : AnyObject]] {
                
                // 进行字典转模型
                var list = [Status]()
                
                for dict in array {
                    list.append(Status(dict: dict))
                }
                //print(array)
                // 字典转模型完成
                //finished(dataList: list, error: nil)
                // 当图片缓存完毕之后在进行回调
                self.cacheImage(list, finished: finished)
            }else {
                finished(dataList: nil, error: nil)
            }
            
        }
        
    }
    
    // MARK: - 缓存微博图片
    // 缓存完毕之后有个回调
    private class func cacheImage(list: [Status], finished: (dataList:[Status]?, error:NSError?) -> () ) {
        // 缓存图片的大小
        var dataLenth = 0
        
        let group = dispatch_group_create()
        
        // 循环微博数组
        for status in list {
            
            // 判断是否有图片，没有图片继续循环
            guard let urls = status.picURLs else {
                continue
            }
            
            for picURL in urls {
                // 入组
                dispatch_group_enter(group)
                // 缓存图片
                SDWebImageManager.sharedManager().downloadImageWithURL(picURL, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) -> Void in
                    
                    let data = UIImagePNGRepresentation(image)!
                    dataLenth += data.length
                    
                    // 出组
                    dispatch_group_leave(group)
                })
                
                
            }
            
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            print("缓存的图片大小为：\(dataLenth / 1024) K")
            finished(dataList: list, error: nil)
        }
    }
    
    // MARK: - 构造方法
    init(dict: [String : AnyObject])
    {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        
        // 判断user，进行字典转模型单独处理
        if key == "user" {
            // 判断value是否是一个有效字典
            if let dict = value as? [String : AnyObject] {
                // 字典转模型，创建用户数据
                user = User(dict: dict)
            }
            // 不加return就会崩
            return
        }
        
        if key == "retweeted_status" {
            if let dict = value as? [String : AnyObject] {
                retweeted_status = Status(dict: dict)
            }
            return
        }
        
        super.setValue(value, forKey: key)
        
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
    
        let properties = ["created_at", "id", "text", "source", "pic_urls"]
        // 模型转字典
        return "\(dictionaryWithValuesForKeys(properties))"
        
    }

}
